package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.PendingAssignmentDTO;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.CourseService;
import org.csu.onlineedubackend.service.StudentAnswerService;
import org.csu.onlineedubackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/teacher")
public class TeacherProfileController {

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;



    @GetMapping("/profile/{teacherId}")
    public CommonResponse<User> getTeacherProfile(@PathVariable Integer teacherId) {
        User user = userService.getById(teacherId);
        // 判断用户是否存在且为教师
        if (user == null || user.getRole() != 2) {
            return CommonResponse.createForError(
                    ResponseCode.USER_NOT_EXIST.getCode(),
                    "教师不存在"
            );
        }
        user.setPassword(null); // 不返回密码
        return CommonResponse.createForSuccess(
                ResponseCode.Success.getCode(),
                "获取教师信息成功",
                user
        );
    }

    @PutMapping("/profile/{teacherId}")
    public CommonResponse<String> updateTeacherProfile(@PathVariable Integer teacherId, @RequestBody Map<String, Object> params) {
        User user = userService.getById(teacherId);
        if (user == null || user.getRole() != 2) {
            return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "教师不存在");
        }
        if (params.containsKey("name")) user.setName((String) params.get("name"));
        if (params.containsKey("username")) user.setUsername((String) params.get("username"));
        if (params.containsKey("phone")) user.setPhone((String) params.get("phone"));
        userService.updateById(user);
        return CommonResponse.createForSuccess(ResponseCode.Success.getCode(), "保存成功", null);
    }

    @PutMapping("/profile/{teacherId}/password")
    public CommonResponse<String> changePassword(@PathVariable Integer teacherId, @RequestBody Map<String, Object> params) {
        User user = userService.getById(teacherId);
        if (user == null || user.getRole() != 2) {
            return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "教师不存在");
        }
        String oldPassword = (String) params.get("oldPassword");
        String newPassword = (String) params.get("newPassword");
        // 校验原密码
        if (!user.getPassword().equals(oldPassword)) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "原密码错误");
        }
        user.setPassword(newPassword);
        userService.updateById(user);
        return CommonResponse.createForSuccess(ResponseCode.Success.getCode(), "密码修改成功", null);
    }

    @GetMapping("/stats/{teacherId}")
    public CommonResponse<Map<String, Object>> getTeacherStats(@PathVariable Integer teacherId) {
        // 1. 查询教师课程总数
        int totalCourses = courseService.countByTeacherId(teacherId);

        // 2. 查询所有课程的学生总数
        int totalStudents = courseService.countStudentsByTeacherId(teacherId);

        // 3. 查询所有课程的平均评分
        Double averageRating = courseService.getAverageRatingByTeacherId(teacherId);

        // 4. 查询所有课程的评价总数
        int totalComments = courseService.countCommentsByTeacherId(teacherId);

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCourses", totalCourses);
        stats.put("totalStudents", totalStudents);
        stats.put("averageRating", averageRating == null ? 0 : averageRating);
        stats.put("totalComments", totalComments);

        return CommonResponse.createForSuccess(
                ResponseCode.Success.getCode(),
                "获取教师统计信息成功",
                stats
        );
    }

    @GetMapping("/recent-courses/{teacherId}")
    public CommonResponse<List<Course>> getRecentlyUpdatedCourses(@PathVariable Integer teacherId) {
        List<Course> recentCourses = courseService.getRecentlyUpdatedCoursesByTeacherId(teacherId);
        return CommonResponse.createForSuccess(
                ResponseCode.Success.getCode(),
                "获取教师最近更新的课程成功",
                recentCourses
        );
    }

    @Autowired
    private StudentAnswerService studentAnswerService;

    // 查询待批改作业（默认3条，全部用参数控制）
    @GetMapping("/pending-assignments")
    public CommonResponse<List<PendingAssignmentDTO>> getPendingAssignments(
            @RequestParam("teacherId") Integer teacherId,
            @RequestParam(value = "all", required = false, defaultValue = "false") String all) {
        boolean showAll = "true".equalsIgnoreCase(all);
        List<PendingAssignmentDTO> list = studentAnswerService.getPendingAssignmentsByTeacher(teacherId, showAll ? null : 3);
        return CommonResponse.createForSuccess(
                ResponseCode.Success.getCode(),
                "获取教师未批改作业成功",
                list
        );
    }
}